package org.osomit.sacct.security.otp.impl;

import org.osomit.sacct.security.otp.impl.HOTPAlgorithm;
import org.osomit.sacct.security.otp.iface.OTPToken;
import org.osomit.sacct.security.utils.Serializer;
import org.osomit.sacct.security.utils.SymmetricCipher;
import org.apache.commons.codec.binary.Base64;

/**
 * generate the OTP Token as a string using given DES password
 *
 * @author Jian Fang (John.Jian.Fang@gmail.com)
 *
 * Date: Jun 26, 2009
 */
public class XMLOTPTokenGenerator {
	private static HOTPAlgorithm algorithm = new HOTPAlgorithm();

	public static String generateToken(String sn, String secret, long counter, long bias, int otpLength,
			boolean addChecksum, int truncationOffset, int stepSize, String password) throws Exception{

		OTPToken token = new OTPTokenImpl(sn, secret.getBytes(), counter, bias, otpLength,
				addChecksum, truncationOffset, stepSize, algorithm);

		return generateToken(token, password);

	}

	public static String generateToken(OTPToken token, String password) throws Exception{
		String result = null;

		if(token != null && password != null){
			byte[] serialized = Serializer.serializeAndCompress(token, true);
			byte[] encrypted = SymmetricCipher.desEncrypt(password, serialized);
			result = new String(Base64.encodeBase64(encrypted), "UTF8");
			System.out.println("Generated Token:\n " + result + "\n");
		}

		return result;
	}
}
